/*
 * Copyright (c) 2017. 上海业晋信息技术有限公司 www.yejinsoft.com
 */

//config的设置是全局的
layui.config({
    base: '/js/plugins/' // 自定义扩展插件所在的目录
}).extend({ //设定模块别名
    yjsloading: 'yjsloading',
});

layui.use(['form', 'yjsloading', 'upload', 'layedit', 'carousel'], function () {
    var $ = layui.jquery
        , form = layui.form
        , yjsloading = layui.yjsloading
        , upload = layui.upload
        , layedit = layui.layedit
        , yjslayer = layui.yjslayer
        , carousel = layui.carousel;

    // 创建carousel轮播控件
    var carouselIndex = carousel.render({
        elem: '#previewCarousel',
        interval: 2000,
    });
    var uploadInst = upload.render({
        elem: '#btnUploadImage'
        ,url: '/upload/scroll/image'
        ,before: function(obj){
            layer.load(0, {
                shade: [0.5, '#FFF']
            }, {time: 5 * 1000});
        }
        ,done: function(res){
            layer.closeAll('loading'); //关闭loading
            if (res.code == 0) {
                //上传成功
                // 为上传成功的文件，添加隐藏域赋值
                $('[name="url"]').val(res.data.src);
                // 修改预览图显示
                $('#coverImages').html('<div><img src='+res.data.src+'></div>');
                carouselIndex.reload({
                    elem: '#previewCarousel',
                    interval: 2000,
                });
                return;
            }
            this.error();
        }
        ,error: function(){
            layer.closeAll('loading'); //关闭loading
            yjslayer.failMsg("滚动图片上传失败！");
        }
    });


    // 自定义表单验证规则
    form.verify({
        order: function (value) {
            if (!/^\d+$/.test(value)) {
                return '只能输入数字';
            }
        },
    });

    // 重新获取验证码
    $('.getLVcode').click(function () {
        var url = '/vcode/path/form';
        yjsloading.loadingCaptcha(url);
    });

    // 监听部门信息表单确定按钮事件
    form.on('submit(toolbarEvent)', function (data) {
        var eventType = data.field.viewType;
        var url, msg = '';
        switch (eventType) {
            case "addData":
                $scrollImageSrc = data.field.url;
                if ($scrollImageSrc.length == 0) {
                    yjslayer.failMsg('请上传图片');
                    return;
                }
                url = '/scroll/images/add';
                msg = '您确定执行本次数据新增操作吗？';
                break;
            case "editData":
                url = '/scroll/images/update';
                msg = '您确定执行本次数据更新操作吗？';
                break;
        }

        $title = '滚动图片维护';
        $url = url;
        $msg = msg;

        yjsloading.ajaxConfirm($title, $msg, $url, data.field, function (result) {
        });
    });

    // 监听个人信息表单取消按钮事件
    $('.cancelEvent').click(function () {
        $title = '滚动图片维护';
        $msg = '您确定取消本次数据更新操作吗？';
        yjsloading.cancelConfirm($title, $msg);
    });
});